<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          月份:
          <NDatePicker input-readonly style="width: 200rem" placeholder="请选择月份"
            v-model:formatted-value="paginationReactive.month" type="month" />
          选择部门:
          <NSelect style="width: 200rem" placeholder="请选择部门" v-model:value="paginationReactive.deptIds" clearable
            :options="bbgDeptList" label-field="name" value-field="value" filterable  />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getDepAttendanceList())">
            查询
          </NButton>
        </NSpace>
        <NSpace align="center">
          <NButton type="primary" style="width: 115rem" @click="exportAttendanceAll" :loading="exportLoading" ghost>
            导出考勤汇总
          </NButton>
          <NButton type="primary" style="width: 115rem" @click="exportAttendance" :loading="exportLoading" ghost>
            导出
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :scroll-x="tableWidth" :loading="tableLoading" remote />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<script setup lang="ts">
import {
  NSpace,
  NButton,
  NDataTable,
  NPagination,
  useMessage,
  NSelect,
  NDatePicker
} from 'naive-ui'
import { reactive, ref, watch, onMounted, h, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { AttendanceModel } from '@/api/attendance'
import type { HttpResponse } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import { useViewerStore } from '@/views/OA/Common/store'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()

let columns: any = []
let columnsList: any = [
  {
    fixed: 'left',
    title: '用户',
    key: 'name',
    width: 100,
    align: useStore.isCenter,
    rowSpan: () => 2
  },
  {
    fixed: 'left',
    title: '部门',
    key: 'dept',
    width: 200,
    align: useStore.isCenter,
    rowSpan: () => 2
  },
  {
    fixed: 'left',
    title: '年份',
    key: 'year',
    width: 60,
    align: useStore.isCenter,
    rowSpan: () => 2
  },
  {
    fixed: 'left',
    title: '月份',
    key: 'month',
    width: 60,
    align: useStore.isCenter,
    rowSpan: () => 2
  }
]
// 上一页下一页
const paginationReactive = reactive<Record<string, any>>({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  month: null, //月份
  deptIds: null, //部门
  onChange: (page: number) => {
    paginationReactive.page = page
    getDepAttendanceList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getDepAttendanceList()
  }
})
//部门
const bbgDeptList: any = ref([])
const getBbgDeptList = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error) return message.error(error.message)
  bbgDeptList.value = res.data
}
//下载
const exportLoading = ref(false)
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
//导出
async function exportAttendance() {
  exportLoading.value = true
  const [error, res, headers] = await sendRequest<HttpResponse>({
    module: 'attendance',
    api: 'aLLAttendanceExport',
    override: {
      params: {
        page: paginationReactive.page,
        limit: 99999,
        month: paginationReactive.month,
        deptIds: paginationReactive.deptIds
      }
    }
  })
  if (error) return message.error(error.message), (exportLoading.value = false)
  download(headers, res, '部门考勤记录')
  message.success('导出成功')
  exportLoading.value = false
}
//导出考勤汇总
async function exportAttendanceAll() {
  exportLoading.value = true
  const [error, res, headers] = await sendRequest<HttpResponse>({
    module: 'attendance',
    api: 'getAllAttendanceRecordStatisticsExcel',
    override: {
      params: {
        month: paginationReactive.month
      }
    }
  })
  if (error) return message.error(error.message), (exportLoading.value = false)
  download(headers, res, '考勤汇总')
  message.success('导出成功')
  exportLoading.value = false
}
// 获取列表
const tableWidth = ref(0)
const tableData = ref([])
const tableLoading = ref(false)
const getDepAttendanceList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<AttendanceModel>>({
    module: 'attendance',
    api: 'allAttendanceList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize * 2,
        month: paginationReactive.month,
        deptIds: paginationReactive.deptIds
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list
  handleData(tableData.value)
  paginationReactive.itemCount = res.data.totalCount / 2
  tableWidth.value = 420 + (getMonthDay(paginationReactive.month) * 90)
}
// 根据日期判断周几
const getWeekDay = function (time: string) {
  let datelist = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return datelist[new Date(time).getDay()]
}
// 处理data
const handleData = (data: any) => {
  if (!data.length) return
  const result: any = []
  data[0].date.map((it: any, index: any) => {
    result.push({
      title: it.day.split('-').at(-1),
      key: 'day',
      align: 'center',
      width: 90,
      render(row: any) {
        return [
          h(
            'div',
            {
              style: {
                backgroundColor: handleTdColor(row.date[index].attendanceStatus),
                padding: '10px',
                width: '100%',
                height: '60px',
                display: 'flex',
                flexWrap: 'wrap',
                alignItems: 'center',
                justifyContent: 'center',
                borderBottom: '2px solid #fff',
                borderRight: '2px solid #fff'
              }
            },
            {
              default: () => {
                return row.date[index].realityTime ? [
                  h('div', { style: { width: '100%' } }, { default: () => row.date[index].attendanceStatus }),
                  h('div', {}, { default: () => row.date[index].realityTime })
                ] : [
                  h('div', {}, { default: () => row.date[index].attendanceStatus })
                  // ? row.date[index].attendanceStatus : ['周六', '周日'].includes(getWeekDay(it.day)) ? '休' : ''
                ]
              }
            }
          )
        ]
      }
    })
  })
  columns = [...columnsList, ...result]
}
// 判断背景色
const handleTdColor = (vc: string) => {
  if (vc == '出差') return '#bb89b1'
  if (vc == '迟到' || vc == '早退') return '#d4ab70'
  if (vc == '公出') return '#88daff'
  if (vc == '加班') return '#44daff'
  if (vc == '旷') return '#ff6944'
  if (vc == '正常' || vc == '休') return undefined
  else if (vc) return '#8f82c1'
}
// 获取月份天数
function getMonthDay(date: any) {
  const year = date.split('-')[0]
  const month = date.split('-')[1]
  let days = new Date(year, month + 1, 0).getDate()
  return days
}

onMounted(() => {
  getBbgDeptList()
  const date = new Date().toLocaleDateString().split('/')
  paginationReactive.month = date[0] + '-' + (Number(date[1]) < 10 ? '0' + date[1] : date[1])
  getDepAttendanceList()
})

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getDepAttendanceList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/Attendance/allAttendance') {
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}

:deep(.n-data-table .n-data-table-td) {
  padding: 0;
}
</style>
